package org.glut.cloud.repairRecordManage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.glut.cloud.repairRecordManage.MaintenanceRecordsdto.MaintenanceRecordsdto;
import org.glut.cloud.repairRecordManage.common.RedisUtil;
import org.glut.cloud.repairRecordManage.service.IMaintenanceRecordsService;
import org.glut.cloud.repairRecordManage.entity.MaintenanceRecords;
import org.glut.cloud.repairRecordManage.mapper.MaintenanceRecordsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  服务实现类
 *
 * @author qjc
 * @since 2024-08-13 11:45
 */
@Service
public class MaintenanceRecordsServiceImpl extends ServiceImpl<MaintenanceRecordsMapper, MaintenanceRecords> implements IMaintenanceRecordsService {
    private static final Logger log = LoggerFactory.getLogger(MaintenanceRecordsServiceImpl.class);


    @Autowired
    MaintenanceRecordsMapper maintenanceRecordsMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;


    @Override
    public Page<MaintenanceRecords> querypages(MaintenanceRecordsdto maintenanceRecordsdto) {
        log.info("条件查询：{}",maintenanceRecordsdto);
        // 创建分页对象
        Page<MaintenanceRecords> page = new Page<>(maintenanceRecordsdto.getPageNo(), maintenanceRecordsdto.getPageSize());
        // 创建查询条件
        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
        if (maintenanceRecordsdto.getFullName()!=null && !maintenanceRecordsdto.getFullName().isEmpty()){
            queryWrapper.like("full_name",maintenanceRecordsdto.getFullName());
        }
        if (maintenanceRecordsdto.getType()!=null && !maintenanceRecordsdto.getType().isEmpty()){
            queryWrapper.eq("type",maintenanceRecordsdto.getType());
        }
        if (maintenanceRecordsdto.getStartTime() != null && maintenanceRecordsdto.getEndTime() != null) {
            queryWrapper.between("repair_time", maintenanceRecordsdto.getStartTime(), maintenanceRecordsdto.getEndTime());
        }
        // 执行分页查询
        return this.maintenanceRecordsMapper.selectPage(page, queryWrapper);
    }

    @Override
    public void deletes(List<Integer> ids) {

    }

    @Override
    public void deleteuser(Integer mainmaintenanceRecordsId) {

    }

    @Override
    public void update(MaintenanceRecordsdto maintenanceRecordsdto) {

    }


    /**
     * 查询维修记录
     * */
    @Override
    public List<MaintenanceRecords> select_1(Integer userNo, String evaStatus) {

        // 1. 创建缓存键
        String cacheKey = "records::all::" + userNo + "_" + evaStatus;

        // 2. 从Redis中获取缓存数据
//        List<MaintenanceRecords> cachedRecords = this.redisTemplate.opsForList().range(cacheKey, 0, -1);
//        List<MaintenanceRecords> cachedRecords =
        List<Object> cachedRecords = this.redisUtil.lGet(cacheKey, 0, -1);
        System.out.println("\n======================= get cache ==========>>");
        cachedRecords.forEach(System.out::println);

        // 3. 检查缓存中是否有数据
        if (cachedRecords != null && !cachedRecords.isEmpty()) {
            log.info("从缓存中获取数据成功！");
            return cachedRecords.stream().map(obj -> {
                Map map = (Map) obj;
                MaintenanceRecords target = new MaintenanceRecords();
                try {
                    BeanUtils.copyProperties(target, obj);
                } catch (IllegalAccessException e) {
                    log.error(" 属性访问异常",e);
                } catch (InvocationTargetException e) {
                    log.error("方法调用异常",e);
                }
                return target;
            }).collect(Collectors.toList());
        }
        System.out.println("\n-------get cache end ----------->\n ");

        // 4.创建查询条件
        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
        if (userNo != null) {
            queryWrapper.lambda().eq(MaintenanceRecords::getUserNo, userNo);
        }
        if (evaStatus != null) {
            queryWrapper.lambda().eq(MaintenanceRecords::getEvaStatus, evaStatus);
        }
        queryWrapper.lambda().eq(MaintenanceRecords::getMaintenanceStatus, "已完成");

        log.info("查询条件：" + queryWrapper.getSqlSegment());
        log.info("查询结果：" + maintenanceRecordsMapper.selectList(queryWrapper));

        // 5.执行数据库查询
        List<MaintenanceRecords> records = maintenanceRecordsMapper.selectList(queryWrapper);
        // 6. 将查询结果存入Redis中
        if (records != null && !records.isEmpty()) {
            this.redisUtil.lSet(cacheKey, records, 60 * 10); // 缓存有效期为10分钟
        }
        return records;
    }

    /**
     * 将评价状态（eva_status）改为已评价
     *
     * @param maintenanceRecordsId
     */
    @Override
    public boolean updateStatus(Integer maintenanceRecordsId) {

        // 1.创建UpdateWrapper对象
        UpdateWrapper<MaintenanceRecords> updateWrapper = new UpdateWrapper();
        // 2.设置更新条件以及更新字段
        updateWrapper.lambda().eq(MaintenanceRecords::getMaintenanceRecordsId, maintenanceRecordsId)
                .set(MaintenanceRecords::getEvaStatus, "已评价");
        // 3.更新
        int result = maintenanceRecordsMapper.update(null, updateWrapper);

        // 4.缓存
//        redisUtil.set("maintenanceRecordsId_" + maintenanceRecordsId, "已评价", 60 * 10);
        return result == 1;
    }
}
